import React, { useRef, useState } from 'react';
import { QRCodeCanvas } from 'qrcode.react';
import html2canvas from 'html2canvas';

const PosterModal = ({ visible, link, onClose, onSaveSuccess }) => {
  const [isSaving, setIsSaving] = useState(false);
  const posterRef = useRef(null);

  if (!visible) return null;

  const savePoster = async () => {
    if (isSaving) return;
    setIsSaving(true);
    try {
      if (!posterRef.current) throw new Error('海报未加载');
      const canvas = await html2canvas(posterRef.current, {
        useCORS: true,
        scale: 2,
        backgroundColor: null
      });
      const link = document.createElement('a');
      link.download = '本草轩理疗坊海报.png';
      link.href = canvas.toDataURL('image/png');
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      onSaveSuccess && onSaveSuccess();
    } catch (error) {
      console.error('保存海报失败:', error);
      alert('保存失败，请尝试截图');
    } finally {
      setIsSaving(false);
    }
  };

  return (
    <div className="qr-modal-overlay">
      <div className="qr-modal poster-modal">
        <div className="qr-modal-header">
          <h3>本草轩理疗坊推广海报</h3>
          <button className="close-btn" onClick={onClose}>×</button>
        </div>
        <div className="qr-modal-content">
          <div className="tcm-poster" ref={posterRef}>
            <img src="/public/icons/haibao.png" alt="本草轩理疗坊宣传图" className="poster-bg" />
            <div className="poster-qr">
              <QRCodeCanvas value={link} size={50} level="H" />
              <p className="qr-tip">扫码注册</p>
            </div>
          </div>
        </div>
        <div className="qr-modal-footer">
          <button className="save-qr-btn" onClick={savePoster} disabled={isSaving}>
            {isSaving ? '保存中...' : '保存海报'}
          </button>
        </div>
      </div>
    </div>
  );
};

export default PosterModal;
